<template>
  <div class="login-home">
    <div class="login-left">
      <img class="login-icon" src="../../assets/login/login-icon.png">
      <img class="login-image" src="../../assets/login/login-image.png">
    </div>
    <div class="login-right">
      <span class="login-title">欢迎来到Chat</span>
      <!-- 登录卡片 -->
      <div v-show="!enroll" class="login-right-body">

        <div style=" height: 15%; width: 100%;display: flex; flex-direction: column; align-items: flex-start;">
          <span style=" margin: 8% 0% 0% 5%; font-size: 2.3vmin; font-weight: bold;">账号密码登录</span>
        </div>

        <div  class="right-body-item">
          <span style=" margin: 5% 0% 0% 5%; font-size: 1.5vmin; color:rgb(97, 97, 97); ">账号:</span>
          <el-input style=" width:85%; height:80%; margin:2% 0% 5% 5%; " @input="userIdCheck" maxlength=20 v-model.number="userId" placeholder="请输入账号"></el-input>
        </div>

        <div  class="right-body-item">
          <span style="margin: 5% 0% 0% 5%; font-size: 1.5vmin; color:rgb(97, 97, 97);">密码:</span>
        <el-input style=" width:85%; height:80%; margin:2% 0% 5% 5%; "  maxlength=20  placeholder="请输入密码" v-model="password" show-password></el-input>
        </div>
        
        <div  class="right-body-item">
          <el-button round @click="login" class="right-body-button">登录</el-button>
        </div>

        <div class="right-body-item" style="flex-direction: row; margin-top: 5%">
          <el-checkbox style=" font-size: 1.5vmin; margin:2% 0% 5% 8%; " v-model="automaticLogin">自动登录</el-checkbox>
          <p id="new-user" @click="enroll=!enroll" style="font-size: 1.5vmin; margin:2% 0% 5% 30%; color:#4a8f12; ">第一次来嘛？注册账号</p>
        </div>
      </div>
      <!-- 注册卡片 -->
      <div v-show="enroll" class="login-right-body">

        <div style=" height: 15%; width: 100%;display: flex; flex-direction: column; align-items: flex-start;">
          <span style=" margin: 8% 0% 0% 5%; font-size: 2.3vmin; font-weight: bold;">注册账号</span>
        </div>

        <div  class="right-body-item">
          <span style=" margin: 5% 0% 0% 5%; font-size: 1.5vmin; color:rgb(97, 97, 97); ">昵称:</span>
          <el-input style=" width:85%; height:80%; margin:2% 0% 5% 5%; " maxlength=8 v-model="registerName" placeholder="请输入8位以内的昵称"></el-input>
        </div>

        <div  class="right-body-item">
          <span style="margin: 5% 0% 0% 5%; font-size: 1.5vmin; color:rgb(97, 97, 97);">密码:</span>
        <el-input style=" width:85%; height:80%; margin:2% 0% 5% 5%; "  maxlength=20  placeholder="请输入20位以内的密码" v-model="registerPassword" show-password></el-input>
        </div>

        <div  class="right-body-item">
          <span style="margin: 5% 0% 0% 5%; font-size: 1.5vmin; color:rgb(97, 97, 97);">确认密码:</span>
        <el-input style=" width:85%; height:80%; margin:2% 0% 5% 5%; "  maxlength=20  placeholder="请再输入一次密码" v-model="finishPassword" show-password></el-input>
        </div>
        
        <div  class="right-body-item">
          <el-button round @click="registerUser" class="right-body-button">注册</el-button>
        </div>

        <div class="right-body-item" >
          <p id="new-user" @click="enroll=!enroll" style="font-size: 1.5vmin; margin:0% 0% 5% 41%; color:#4a8f12; ">返回登录</p>
        </div>
      </div>


    </div>

  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'LoginHome',
  data(){
    return {
      userId: '', // uid
      userName:"", // 昵称
      password:'', // 登录时密码
      registerName:'', // 注册时昵称
      registerPassword:'', // 注册时密码
      finishPassword:'', // 注册时确定密码
      enroll:false, // 是否切换到注册页面
      automaticLogin:true // 是否自动登录
    }
  },
  methods:{
    // 保证只接收数字
    // 上面用@input不用加(value)就可以收到数据(也不能加,不然会因为语法错误失效)
    // 这种方式最好，也最直接、最适用
    userIdCheck(value){
      this.userId = value.replace(/[^0-9]/g, '');
    },
    login(){
      // 判断数据是否正常
      if(this.userId.trim()==''||this.password.trim()==''){
        this.$message({
                  message: '账号或密码不能为空哦!',
                  type: 'error'
                });
        return;
      }
      // 组装数据
      // 这个是外壳
      let sendData =new this.$protobufClass.PackageInfo();
      // 主要数据
      let data = new this.$accountNumber.AccountNumber();
      data.setUid(this.userId.trim());
      data.setPassword(this.password.trim());
      // 填充并转为字节数组
      sendData.setAccountnumber(data);
      sendData=sendData.serializeBinary();
      
      
      // 发送请求
      axios.post('/accountNumbers/login',sendData,{
        headers: {
        'Content-Type': 'application/x-protobuf' // 加上protobuf需要得请求头
        },
        responseType: 'arraybuffer',
      }).then(res=>{
        // 将收到的数据转为protobuf对象
        const lastData=this.$protobufClass.PackageInfo.deserializeBinary(new Uint8Array(res.data)).toObject();
        // 验证登录结果
        if(lastData.code==200){
          localStorage.setItem('token',lastData.token);
          // 这里给session也存一个true，本次浏览器关闭后就会清除
          // 跳转页面时会根据这两个数据判断状态,具体可看前置路由守卫
          localStorage.setItem('automaticLogin',this.automaticLogin);
          sessionStorage.setItem('sessionAutomaticLogin',true);
          this.$router.push({name: 'chat'})
        }else{
           this.$message({
                  message: "登录失败，请检查账号和密码",
                  type: 'error'
                });
        }
        
      })
      .catch((error) => {
          this.$message({
                message: '失败了哦!',
                type: 'error'
              });
          error=this.$protobufClass.PackageInfo.deserializeBinary(new Uint8Array(error)).toObject();
          console.log(error);

        });

    },
    // 注册并登录
    registerUser(){
      // 验证注册信息
      if(this.registerPassword.trim() != this.finishPassword.trim() && (this.registerPassword.trim() == '')){
          this.$message({
                  message: '两次密码不一致或密码为空',
                  type: 'warning'
                });
      }else if(this.registerName.trim() == '' ||this.registerName.trim().length > 8){
        this.$message({
                  message: '昵称不能为空或者超过8位哦',
                  type: 'warning'
                });
      }else{
        
        let sendData=new this.$protobufClass.PackageInfo();
        let data=new this.$accountNumber.AccountNumber();
        data.setName(this.registerName)
        data.setPassword(this.registerPassword.trim())
        sendData.setAccountnumber(data);
        sendData=sendData.serializeBinary();

        axios.post('/accountNumbers/register',sendData,{
          headers:{
            'Content-Type': 'application/x-protobuf'
          },
          responseType: 'arraybuffer'
        }).then(res=>{
          let lastData=this.$protobufClass.PackageInfo.deserializeBinary(new Uint8Array(res.data)).toObject();
          if(lastData.code==200){
              localStorage.setItem('token',lastData.token);
              localStorage.setItem('automaticLogin',this.automaticLogin);
              sessionStorage.setItem('sessionAutomaticLogin',true);
              this.$router.push({name: 'chat'})
          }else{
            this.$message({
                  message: lastData.msg,
                  type: 'error'
                })
          }

        }).catch(err=>{
          err=this.$protobufClass.PackageInfo.deserializeBinary(new Uint8Array(err)).toObject();
          console.log(err)
          this.$message({
                  message: '失败了哦!',
                  type: 'error'
                })
        })
      }
    }
  }
}
</script>

<style scoped>
#new-user:hover{
  /* 鼠标悬浮时给手展示的效果 */
  cursor: pointer;
}

.right-body-button{
  margin: 8% 0% 0% 5%;
  width: 85%;
  height: 45%;
  background-color:#78c936; 
  border-radius: 10px;
  color: black;
  font-weight: bold;
}
.right-body-item{
  height: 20%; 
  width: 100%;
  display: flex;
  /* 元素上下排列 */
  flex-direction: column; 
  /* 不要拉伸内部 */
  align-items: flex-start;
}
.login-title {
    margin: 18% 0% 0% 28%;
    font-size: 5vmin;
    font-weight: bold;
}
.login-right {
  width: 45vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.login-right-body{
  margin: 2% 0% 0% 20%;
  width: 50%;
  height: 50%;
  border: 1px;
  border-radius: 10px;
  background: white;
  box-shadow: 0 0 3px 2px #d8ecd5, 0 0 2px 1px rgba(184, 184, 184, 0.4);
}
.login-left {
  width: 50vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.login-icon {
  width: 20%;
  height: 10%;
  margin: 5% 0% 0% 80%;
}
.login-image {
  width: 80%;
  height: 80%;
  margin-left: 10%;
}
.login-home {
  display: flex;
  height: 100vh;
  width: 100vw;
  background-image: url("../../assets/login/login-back.png");
   background-size: cover;
  background-position: center;
}

</style>
